package com.binvshe.binvshe.app.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ui.LoginActivity;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.web.RuleActivity;
import com.binvshe.binvshe.common.web.WebActivity;
import com.binvshe.binvshe.entity.ChannelsEntity;
import com.binvshe.binvshe.opus.SearchOpusActivity;
import com.binvshe.binvshe.release.ChooseReleaseActivity;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.Bundler;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
import com.pachong.android.baseuicomponent.fragment.BaseFragment;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ValueEntity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.binvshe.binvshe.app.home.HomeListFragment.KEY_CHANNELID;
import static com.pachong.android.framework.picture.browser.constant.Constant.REQUEST_CODE;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/8/25
 */
public class HomeFragment extends BaseFragment {
    private static final int GETCODE = 1;
    @Bind(R.id.vptab_home)
    SmartTabLayout mVptabHome;
    @Bind(R.id.vp_home)
    ViewPager mVpHome;


    @OnClick({R.id.ivRelease,R.id.ivScan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivRelease:
                if (AccountManager.getCurrentAccount() == null) {
                    LoginActivity.start(getActivity());
                } else {
//                   ClubReleaseActivity.start(getContext());
                    ChooseReleaseActivity.start(getActivity(), -1);
                }
                break;
            case R.id.ivScan:
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==CodeUtils.RESULT_GAME){
            RuleActivity.start(getActivity());
        }else{
            String result = data.getStringExtra(CodeUtils.RESULT_STRING);
            int type = data.getIntExtra(CodeUtils.TYPE, 0);
            if(type==CodeUtils.RESULT_GET){
                getCode(result);
            }else if(type==CodeUtils.RESULT_PAY){
                showCacheDialog(result);
            }else if(type==CodeUtils.RESULT_WEB){
                WebActivity.start(getActivity());
            }else if(type==CodeUtils.RESULT_GAME){
                RuleActivity.start(getActivity());
            }
        }
    }

    private void getCode(String result) {
        //获得萌都币
        Log.e("resultresult",result);
        MyHttpRequest request = new MyHttpRequest(getContext());
        String url = String.format(UrlCenter.GET_SCAN, result);
        request.put(url, null, new DataRequestListener<ValueEntity>(ValueEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(ValueEntity o) {
                super.onSuccess(o);
                EasyToast.showToast(getContext(),"获得"+o.getValue()+"个萌都币");
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                if(strMsg.equals("未知错误")){
                    LoginActivity.start(getActivity());
                    EasyToast.showToast(getContext(),"请登录后操作");
                }else{
                    EasyToast.showToast(getContext(),strMsg);
                }
            }
        });
    }


    private void showCacheDialog(final String result) {
            final AlertDialogFragment getDialogFragment = new AlertDialogFragment();
          getDialogFragment.setMessage("确认支付"+result+"个萌都币？")
                  . setPositiveButton("确定", new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                        payCoin(result);
                        getDialogFragment.dismiss();
                      }
                  })
                  .setNegativeButton("取消", new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          getDialogFragment.dismiss();
                      }
                  }).show(getFragmentManager());
        }

    //支付萌都币
    private void payCoin(String result) {
        MyHttpRequest requrst = new MyHttpRequest(getActivity());
        String resu =String.format(UrlCenter.PAY_SCAN, result);
        requrst.put(resu, null, new DataRequestListener<Object>(Object.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                EasyToast.showToast(getContext(),"支付成功");
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                if(strMsg.equals("未知错误")){
                    LoginActivity.start(getActivity());
                    EasyToast.showToast(getContext(),"请登录后操作");
                }else{
                    EasyToast.showToast(getContext(),strMsg);
                }
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initTitle();
        initData(new ArrayList<ChannelsEntity>());
        getChanelList();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public HomeFragment() {
        setRetainInstance(true);  //转屏不需要重新创建
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, null);
    }

    private void initTitle() {
//        getCustomToolbar().setVisibility(View.GONE);
        showToolbar();
        getCustomToolbar().setTitle("首页");
        getCustomToolbar().addRightImageButton(R.mipmap.icon_release, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AccountManager.getCurrentAccount() == null) {
                    LoginActivity.start(getActivity());
                } else {
//                    ClubReleaseActivity.start(getContext());
                    ChooseReleaseActivity.start(getActivity(), -1);
                }
            }
        });

        hideToolbar();
    }

    private void initData(List<ChannelsEntity> channelsEntities) {
        FragmentPagerItems.Creator items = FragmentPagerItems.with(getContext())
                .add("热门", HotOpus1Fragment.class).add("关注", FollowOpusFragment.class);
//                .add("最新作品", NewOpusFragment.class).add("社团推荐", RecommendFragemt.class);
        //遍历添加
        for (ChannelsEntity channelsEntity : channelsEntities) {
            if (channelsEntity.getId() != -1) {
                items.add(channelsEntity.getName(), HomeListFragment.class,
                        new Bundler().putInt(KEY_CHANNELID, channelsEntity.getId()).get());
            }
        }

        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(getChildFragmentManager(), items.create());
        mVpHome.setAdapter(adapter);
        mVptabHome.setViewPager(mVpHome);
    }

    /**
     * 获得频道列表
     */
    public void getChanelList() {
        IHttpRequest request = new MyHttpRequest(getContext());
        request.get(UrlCenter.HOME_CHANNEL_LIST, null, new DataRequestListener<List<ChannelsEntity>>(ChannelsEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<ChannelsEntity> o) {
                super.onSuccess(o);
                initData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    @OnClick(R.id.btnSearch)
    public void onClick() {
        SearchOpusActivity.start(getActivity(), -1);
    }
}
